package com.restaurant.application.util;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.nebutown.commonunits.utils.SnowFlake;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class WeChatCode {

    private static final Logger LOG = LoggerFactory.getLogger(WeChatCode.class);
    private static final String accessKey = Constant.ACCESSKEY;

    private static final String secretKey = Constant.SECRETKEY;

    private static final String bucket = Constant.BUCKET;

    private static final String domain = Constant.DOMAIN;


    public static String getminiQr(String sceneStr, String accessToken) {
        InputStream inputStream = null;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", sceneStr);
            LOG.info("调用生成微信URL接口传参:{},accessToken:{}", param, accessToken);

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // 接口
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            //必须是json模式的 post
            String body = JSON.toJSONString(param);
            StringEntity entity;
            entity = new StringEntity(body);
            entity.setContentType("image/jpg");

            httpPost.setEntity(entity);
            HttpResponse response;

            response = httpClient.execute(httpPost);
            inputStream = response.getEntity().getContent();

            //上传至资源服务器生成url
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //缓冲数组
            byte[] bs = new byte[1024];
            int len = -1;

            while ((len = inputStream.read(bs)) != -1) {
                byteArrayOutputStream.write(bs, 0, len);
            }

            byte[] bytes = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            inputStream.close();

            // 上传字节数组至七牛云服务器
            String domainAndKey = uploadFilesViaServer(bytes);

            LOG.info("MiniProgramCodeUtils.getWxacode ========= 域名+Key：{} ========= ", domainAndKey);

            if (!Strings.isNullOrEmpty(domainAndKey)) {
                String[] dKeyArray = domainAndKey.split(",");
                if (dKeyArray.length > 1) {
                    return "https://" + dKeyArray[0] + "/" + dKeyArray[1];
                }
                return null;
            } else {
                LOG.info("MiniProgramCodeUtils.getWxacode ======== 小程序码生成错误，请稍后重试！========");
            }

        } catch (Exception e) {
            LOG.error("调用小程序生成微信永久小程序码URL接口异常", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    static String uploadFilesViaServer(byte[] uploadBytes) {

        String retKey = "";

        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());

        UploadManager uploadManager = new UploadManager(cfg);

        String uuid = SnowFlake.findUniqueId();

        // 等同于文件名
        String key = uuid + ".jpg";

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            retKey = putRet.key;

        } catch (QiniuException ex) {
            Response r = ex.response;
            LOG.debug(r.toString());
            try {
                LOG.debug(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return domain + "," + retKey;
    }

}
